/**
 * @Time    : 2022/03/10 14:11
 * @Author  : WanRongJia
 * @License : Software business license
 * @Site    : www.rich-f.com
 * @File    : buildTreeData.js
 * @Software: Rich Web Platform
 * @Function: 构建树形结构
 * @Version : 1.0
 **/

const buildTreeData = function (items = [], key, parentKey) {
	return new Promise((resolve, reject) => {
		const result = []; // 存放结果集
		const itemMap = {}; // 存放对象集
		for (const item of items) {
			const id = item[key];
			const pid = item[parentKey];

			if (!itemMap[id]) {
				itemMap[id] = {
					children: [],
				};
			}
			itemMap[id] = {
				...item,
				children: itemMap[id]["children"],
			};
			const treeItem = itemMap[id];
			if (!pid) {
				result.push(treeItem);
			} else {
				if (!itemMap[pid]) {
					itemMap[pid] = {
						children: [],
					};
				}
				itemMap[pid].children.push(treeItem);
			}
		}
		resolve(result);
	});
};

module.exports = { buildTreeData };
